package com.pafcio.dde.server;

import java.util.TooManyListenersException;

import com.neva.DdeException;
import com.neva.DdeServer;
import com.neva.DdeServerConnectionEventListener;
import com.neva.DdeServerTransactionEventListener;
import com.pafcio.dde.shared.ConversationDetails;


public class DDEServer extends DdeServer{

	private TimeGenerationStrategy timeGenerationStrategy;
	protected boolean isRunning;
	private final ConversationDetails conversationDetails;
	private String topic;

	public DDEServer(String service, String topic, ConversationDetails conversationDetails, TimeGenerationStrategy timeGenerationStrategy, DataGenerationStrategy dataGenerationStrategy) {
		this.setService(service);
		this.topic = topic;
		this.conversationDetails = conversationDetails;
		this.timeGenerationStrategy = timeGenerationStrategy;
				
		tryAddDdeServerConnectionEventListener(new NoOpConnectionEventListener());
		tryAddDdeServerTransactionEventListener(new DataGenerationStrategyEventListener(dataGenerationStrategy));
	}
	
	@Override
	public void start(){
		isRunning = true;
		tryToStart();
		generate();
	}
	
	@Override
	public void stop() {
		isRunning = false;
		super.stop();
	}
	
	private void tryToStart() {
		try {
			super.start();
		} catch (DdeException e) {
			e.printStackTrace();
		}
	}

	protected void generate() {		
		while(isRunning && timeGenerationStrategy.getCanContinue()){
			postItems();			
			doAfterPostingActions();
		}
	}
	
	protected void postItems() {
		for(String item : conversationDetails.getItems())
			postAdvise(topic, item);
	}
		
	private void doAfterPostingActions() {
		timeGenerationStrategy.doAfterPostingActions();
	}
	
	private void tryAddDdeServerConnectionEventListener(DdeServerConnectionEventListener listener){
		try {
			addDdeServerConnectionEventListener(listener);
		} catch (TooManyListenersException e) {
			e.printStackTrace();
		}
	}

	private void tryAddDdeServerTransactionEventListener(DdeServerTransactionEventListener listener) {
		try {
			addDdeServerTransactionEventListener(listener);
		} catch (TooManyListenersException e) {
			e.printStackTrace();
		}
	}			
}
